﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "BOM详情";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<div style="padding: 20px; height: 100vh; display: flex; flex-direction: column;">
    <!-- 上部分：产品名称 -->
    <div style="margin-bottom: 20px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h2 id="productTitle" style="margin: 0; color: #333;">BOM详情</h2>
            <div>
                <button class="layui-btn layui-btn-warm" id="backToList">
                    <i class="layui-icon layui-icon-left"></i> 返回列表
                </button>
                            <a href="/Home/Index" class="layui-btn layui-btn-primary">
                <i class="layui-icon layui-icon-home"></i> 返回主页
            </a>
            </div>
        </div>
    </div>
    
    <!-- 下部分：标签页 -->
    <div style="flex: 1; overflow: hidden;">
        <div class="layui-tab layui-tab-brief" lay-filter="bomTab" style="height: 100%;">
            <ul class="layui-tab-title">
                <li class="layui-this">BOM信息</li>
                <li>BOM配件</li>
                <li>工艺流程</li>
                <li>操作记录</li>
            </ul>
            <div class="layui-tab-content" style="height: calc(100% - 50px); overflow: hidden;">
                <!-- BOM信息标签页 -->
                <div class="layui-tab-item layui-show" style="height: 100%; overflow-y: auto;">
                    <div class="layui-row" style="margin-top: 20px;">
                        <div class="layui-col-md12">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>基础信息</h3>
                                </div>
                                <div class="layui-card-body">
                                    <table class="layui-table" lay-skin="line">
                                        <tbody>
                                            <tr>
                                                <td style="width: 120px; font-weight: bold;">BOM编号:</td>
                                                <td id="bomNumber">BOM0000457</td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">默认BOM:</td>
                                                <td id="defaultBOM">否</td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">成品类型:</td>
                                                <td id="productType">类型一</td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">日产量:</td>
                                                <td id="dailyOutput">50</td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">预估成本:</td>
                                                <td id="estimatedCost">8,000</td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">BOM描述:</td>
                                                <td id="bomDesc"></td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">BOM主题:</td>
                                                <td id="bomTheme"></td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">版本:</td>
                                                <td id="bomVersion"></td>
                                            </tr>
                                            <tr>
                                                <td style="font-weight: bold;">成品名称:</td>
                                                <td id="productName"></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- BOM配件标签页 -->
                <div class="layui-tab-item" style="height: 100%; overflow-y: auto;">
                    <div class="layui-card" style="margin-top: 20px;">
                        <div class="layui-card-header">
                            <h3>BOM配件列表</h3>
                        </div>
                        <div class="layui-card-body">
                            <table id="bomMaterialTable" lay-filter="bomMaterialTable"></table>
                        </div>
                    </div>
                </div>
                
                <!-- 工艺流程标签页 -->
                <div class="layui-tab-item" style="height: 100%; overflow-y: auto;">
                    <div class="layui-card" style="margin-top: 20px;">
                        <div class="layui-card-header">
                            <h3>工艺流程</h3>
                        </div>
                        <div class="layui-card-body">
                            <table id="craftTable" lay-filter="craftTable"></table>
                        </div>
                    </div>
                </div>
                
                <!-- 操作记录标签页 -->
                <div class="layui-tab-item" style="height: 100%; overflow-y: auto;">
                    <div class="layui-card" style="margin-top: 20px;">
                        <div class="layui-card-header">
                            <h3>操作记录</h3>
                        </div>
                        <div class="layui-card-body">
                            <table id="opLogTable" lay-filter="opLogTable"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
layui.use(['element', 'layer', 'table'], function(){
    var element = layui.element;
    var layer = layui.layer;
    var table = layui.table;
    
    // 获取URL参数中的bomId
    var urlParams = new URLSearchParams(window.location.search);
    var bomId = urlParams.get('bomId');
    
    if (!bomId) {
        layer.msg('缺少BOM ID参数', {icon: 2});
        return;
    }
    
    // 加载BOM详情数据
    function loadBOMDetail() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetOneBOM?BOMId=' + bomId,
            type: 'GET',
            success: function(response) {
                console.log('获取BOM详情成功:', response);
                if (response.code === 200 && response.data) {
                    var bomData = response.data;
                    
                    // 设置产品标题
                    $('#productTitle').text(bomData.productName + 'BOM');
                    
                    // 填充基础信息
                    $('#bomTheme').text(bomData.bomtheme || bomData.boMtheme || bomData.BOMtheme || '');
                    $('#bomVersion').text(bomData.bomVersion || bomData.BOMVersion || '');
                    $('#productName').text(bomData.productName || '');
                    $('#productType').text(bomData.productType || '');
                    $('#bomDesc').text(bomData.bomDesc || bomData.BOMDesc || '');
                    
                    // 加载该产品的物料列表
                    loadBOMMaterials(bomData.productId);
                    // 加载该产品的工艺流程
                    loadCraft(bomData.productId);
                    // 加载该产品的操作记录
                    loadOperationLogs(bomData.productId);
                    
                } else {
                    layer.msg(response.msg || '获取BOM详情失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                console.error('获取BOM详情失败:', error);
                layer.msg('获取BOM详情失败: ' + error, {icon: 2});
            }
        });
    }
    
    // 加载工艺流程
    function loadCraft(productId) {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetCraft?ProductId=' + productId,
            type: 'GET',
            success: function(response) {
                console.log('获取工艺流程成功:', response);
                if (response.code === 200 && response.data) {
                    renderCraftTable(response.data);
                } else {
                    layer.msg(response.msg || '获取工艺流程失败', {icon: 2});
                    renderCraftTable([]);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取工艺流程失败:', error);
                layer.msg('获取工艺流程失败: ' + error, {icon: 2});
                renderCraftTable([]);
            }
        });
    }

    // 渲染工艺流程表格
    function renderCraftTable(rows) {
        table.render({
            elem: '#craftTable',
            data: rows,
            cols: [[
                {field: 'orderNo', title: '加工顺序', width: 100, sort: true, templet: function(d){
                    return d.orderNo || d.processOrder || d.order || '';
                }},
                {field: 'craftCode', title: '工序编码', width: 140, templet: function(d){
                    return d.craftCode || d.code || '';
                }},
                {field: 'craftName', title: '工序名称', width: 200, templet: function(d){
                    return d.craftName || d.name || '';
                }},
                {field: 'process', title: '工艺流程', width: 220, templet: function(d){
                    return d.process || '';
                }},
                {field: 'order', title: '加工顺序', width: 160, templet: function(d){
                    return d.order || d.orderNo || d.processOrder || d.order_number || '';
                }},
                {field: 'leader', title: '负责人', width: 120, templet: function(d){
                    return d.leader || '';
                }},
                {field: 'department', title: '部门', width: 140, templet: function(d){
                    return d.department || '';
                }},
                {field: 'workLoad', title: '单位工作量', width: 120, templet: function(d){
                    return d.workLoad || d.workload || d.unitWorkload || '';
                }}
            ]],
            page: true,
            limit: 10,
            height: 400,
            text: { none: '暂无工艺流程数据' },
            done: function(res, curr, count) {
                console.log('工艺流程表格渲染完成，数据条数:', count);
            }
        });
    }

    // 加载操作记录
    function loadOperationLogs(productId) {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetBOMOne?ProductId=' + productId,
            type: 'GET',
            success: function(response) {
                console.log('获取操作记录成功:', response);
                if (response.code === 200 && response.data) {
                    renderOperationLogTable(response.data);
                } else {
                    layer.msg(response.msg || '获取操作记录失败', {icon: 2});
                    renderOperationLogTable([]);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取操作记录失败:', error);
                layer.msg('获取操作记录失败: ' + error, {icon: 2});
                renderOperationLogTable([]);
            }
        });
    }

    // 渲染操作记录表格
    function renderOperationLogTable(rows) {
        table.render({
            elem: '#opLogTable',
            data: rows,
            cols: [[
                {field: 'bomId', title: '序号', width: 100, sort: true},
                {field: 'creteName', title: '操作人', width: 140, templet: function(d){
                    return d.creteName || d.createName || d.operator || '';
                }},
                {field: 'creteDate', title: '操作时间', width: 200, templet: function(d){
                    var val = d.creteDate || d.createDate || d.createdAt || '';
                    if (!val) return '';
                    try {
                        var date = new Date(val);
                        if (!isNaN(date.getTime())) {
                            var y = date.getFullYear();
                            var m = (date.getMonth() + 1).toString().padStart(2, '0');
                            var day = date.getDate().toString().padStart(2, '0');
                            var hh = date.getHours().toString().padStart(2, '0');
                            var mm = date.getMinutes().toString().padStart(2, '0');
                            var ss = date.getSeconds().toString().padStart(2, '0');
                            return y + '-' + m + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
                        }
                    } catch (e) {}
                    return val;
                }},
                {field: 'createDesc', title: '操作记录', minWidth: 260, templet: function(d){
                    return d.createDesc || d.desc || '';
                }}
            ]],
            page: true,
            limit: 10,
            height: 400,
            text: { none: '暂无操作记录' }
        });
    }

    // 加载BOM物料列表
    function loadBOMMaterials(productId) {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetBOMOne?ProductId=' + productId,
            type: 'GET',
            success: function(response) {
                console.log('获取BOM物料列表成功:', response);
                if (response.code === 200 && response.data) {
                    // 调试：打印第一条数据的字段信息
                    if (response.data.length > 0) {
                        console.log('第一条物料数据的所有字段:', Object.keys(response.data[0]));
                        console.log('第一条物料数据内容:', response.data[0]);
                    }
                    
                    // 获取物料详细信息
                    enrichMaterialData(response.data);
                } else {
                    layer.msg(response.msg || '获取BOM物料列表失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                console.error('获取BOM物料列表失败:', error);
                layer.msg('获取BOM物料列表失败: ' + error, {icon: 2});
            }
        });
    }
    
    // 获取物料详细信息并合并数据
    function enrichMaterialData(bomData) {
        // 获取所有不重复的物料ID
        var materialIds = [];
        bomData.forEach(function(item) {
            if (item.materialId && materialIds.indexOf(item.materialId) === -1) {
                materialIds.push(item.materialId);
            }
        });
        
        if (materialIds.length === 0) {
            renderBOMMaterialsTable(bomData);
            return;
        }
        
        // 调用物料详情API获取详细信息
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetMaterial',
            type: 'GET',
            success: function(response) {
                console.log('获取物料详情成功:', response);
                if (response.code === 200 && response.data) {
                    // 创建物料ID到详情的映射
                    var materialMap = {};
                    response.data.forEach(function(material) {
                        materialMap[material.materialId] = material;
                    });
                    
                    // 合并BOM数据和物料详情
                    var enrichedData = bomData.map(function(bomItem) {
                        var materialDetail = materialMap[bomItem.materialId];
                        if (materialDetail) {
                            return {
                                ...bomItem,
                                materialName: materialDetail.materialName || materialDetail.MaterialName || '',
                                specification: materialDetail.specification || materialDetail.Specification || '',
                                unitName: materialDetail.unitName || materialDetail.UnitName || '',
                                brand: materialDetail.brand || materialDetail.Brand || ''
                            };
                        } else {
                            return bomItem;
                        }
                    });
                    
                    console.log('合并后的数据:', enrichedData);
                    renderBOMMaterialsTable(enrichedData);
                } else {
                    // 如果获取物料详情失败，直接渲染原始数据
                    renderBOMMaterialsTable(bomData);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取物料详情失败:', error);
                // 如果获取物料详情失败，直接渲染原始数据
                renderBOMMaterialsTable(bomData);
            }
        });
    }
    
    // 渲染BOM物料表格
    function renderBOMMaterialsTable(materials) {
        table.render({
            elem: '#bomMaterialTable',
            data: materials,
            cols: [[
                {field: 'materialId', title: '物料ID', width: 100, sort: true},
                {field: 'materialName', title: '物料名称', width: 200, templet: function(d){
                    var materialName = d.materialName || d.MaterialName || d.material_name || '';
                    return '<div style="white-space: normal; word-wrap: break-word; line-height: 1.4;">' + materialName + '</div>';
                }},
                {field: 'specification', title: '规格型号', width: 300, templet: function(d){
                    var specification = d.specification || d.Specification || d.spec || '';
                    return '<div style="white-space: normal; word-wrap: break-word; line-height: 1.4;">' + specification + '</div>';
                }},
                {field: 'unitName', title: '单位', width: 100, templet: function(d){
                    return d.unitName || d.UnitName || d.unit_name || d.unit || '';
                }},
                {field: 'brand', title: '品牌', width: 150, templet: function(d){
                    return d.brand || d.Brand || '';
                }},
                {field: 'partNum', title: '配件数量', width: 120},
                {field: 'lossRate', title: '损耗率', width: 120}
            ]],
            page: true,
            limit: 15,
            limits: [15, 30, 50, 100],
            height: 400,
            text: {
                none: '暂无物料数据'
            },
            done: function(res, curr, count) {
                console.log('物料表格渲染完成，数据条数:', count);
                if (res.data && res.data.length > 0) {
                    console.log('表格渲染后的第一条数据:', res.data[0]);
                }
            }
        });
    }
    
    // 返回列表按钮
    $('#backToList').on('click', function(){
        window.location.href = '/Home/GetBOM';
    });
    
    // 页面加载完成后加载数据
    $(document).ready(function(){
        loadBOMDetail();
    });
});
</script>

<style>
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
}

h2 {
    color: #333;
    font-size: 24px;
    font-weight: bold;
}

h3 {
    color: #333;
    font-size: 16px;
    font-weight: bold;
    margin: 0;
}

.layui-card {
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.layui-card-header {
    background-color: #f8f8f8;
    border-bottom: 1px solid #e6e6e6;
    padding: 15px 20px;
}

.layui-card-body {
    padding: 20px;
}

.layui-table {
    font-size: 14px;
}

.layui-table td, .layui-table th {
    padding: 12px 8px;
    vertical-align: middle;
}

.layui-table-cell {
    height: auto !important;
    line-height: 1.4 !important;
    padding: 8px 12px !important;
    white-space: normal !important;
    word-wrap: break-word !important;
}

.layui-tab-title {
    background-color: #fff;
    border-bottom: 1px solid #e6e6e6;
}

.layui-tab-title li {
    padding: 0 20px;
    font-size: 14px;
}

.layui-tab-content {
    background-color: #fff;
}

.layui-btn {
    margin-right: 10px;
}

.layui-btn:last-child {
    margin-right: 0;
}

/* 标签页内容区域样式 */
.layui-tab-item {
    padding: 20px;
}


</style>
